package com.tencent.sr.iris.activity.service.event.impl;

import com.alibaba.fastjson.JSON;
import com.tencent.sr.iris.activity.interfaces.enums.ActivityEventSourceEnum;
import com.tencent.sr.iris.activity.interfaces.enums.ActivityEventTypeEnum;
import com.tencent.sr.iris.activity.interfaces.event.dto.ActivityEventDTO;
import com.tencent.sr.iris.activity.interfaces.message.DistributionOrderEvent;
import com.tencent.sr.iris.activity.service.config.ActivityConfig;
import com.tencent.sr.iris.activity.service.event.EventStandardService;
import com.tencent.sr.iris.activity.service.event.vo.DistributionOrderAggrVO;
import com.tencent.sr.iris.activity.service.kafka.KafkaMsgSender;
import com.tencent.sr.iris.activity.service.util.IdCreateorUtil;
import com.tencent.sr.iris.user.core.service.interfaces.enums.UserLevelEnum;
import com.tencent.sr.iris.user.core.service.interfaces.request.message.UserActivityLevelUpRequest;
import com.tencent.sr.iris.user.core.service.interfaces.request.message.UserSupervisorChangeRequest;
import com.tencent.sr.iris.user.core.service.interfaces.request.tag.SpecialLeaderTagMqRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class EventStandardServiceImpl implements EventStandardService {

    @Resource
    private KafkaMsgSender kafkaMsgSender;

    @Resource
    private IdCreateorUtil idCreateorUtil;

    @Value("${kafka.topics.activityEventTopic}")
    private String activityEventTopic;

    @Value("${kafka.topics.activityLowerPriorityEventTopic}")
    private String activityLowerPriorityEventTopic;

    @Resource
    private ActivityConfig activityConfig;

    @Override
    public void handleUserActivityLevelUpMsg(UserActivityLevelUpRequest request) {
        if (Objects.nonNull(request)) {
            ActivityEventDTO activityEventDTO = new ActivityEventDTO();
            String afterLevelId = request.getAfterLevelId();
            if (UserLevelEnum.TRAINEE.getValue().equals(afterLevelId)) {
                activityEventDTO.setEventType(ActivityEventTypeEnum.BECOME_TRAINEE.getCode());
            } else if (UserLevelEnum.isGroup(afterLevelId)) {
                activityEventDTO.setEventType(ActivityEventTypeEnum.LEVEL_UP.getCode());
            }
            activityEventDTO.setIdempotent(idCreateorUtil.genId());
            activityEventDTO.setUid(request.getUid());
            activityEventDTO.setEventInfo(JSON.toJSONString(request));
            activityEventDTO.setEventSource(ActivityEventSourceEnum.USER_REPORT.getCode());
            Date date = new Date();
            activityEventDTO.setCreateTime(date.getTime());
            if (Objects.nonNull(request.getTimeStamp())) {
                activityEventDTO.setEventTime(request.getTimeStamp());
            } else {
                activityEventDTO.setEventTime(date.getTime());
            }
            sendStandardEventMsg(activityEventDTO);
        }
    }

    @Override
    public void handleUserSupervisorChangeMsg(UserSupervisorChangeRequest request) {
        if (Objects.nonNull(request)) {
            ActivityEventDTO activityEventDTO = new ActivityEventDTO();
            activityEventDTO.setEventType(ActivityEventTypeEnum.SUPERVISOR_CHANGE.getCode());
            activityEventDTO.setUid(request.getUid());
            activityEventDTO.setPid(request.getPid());
            activityEventDTO.setEventInfo(JSON.toJSONString(request));
            activityEventDTO.setEventSource(ActivityEventSourceEnum.USER_REPORT.getCode());
            Date date = new Date();
            activityEventDTO.setCreateTime(date.getTime());
            if (Objects.nonNull(request.getTimeStamp())) {
                activityEventDTO.setEventTime(request.getTimeStamp());
            } else {
                activityEventDTO.setEventTime(date.getTime());
            }
            activityEventDTO.setIdempotent(idCreateorUtil.genId());
            sendStandardEventMsg(activityEventDTO);
        }
    }

    @Override
    public void handleSpecialInviteMsg(SpecialLeaderTagMqRequest request) {
        if (Objects.nonNull(request)) {
            String uid = request.getUid();
            Date date = new Date();
            //特邀打标事件的事件是s，这里转成ms
            Long eventTime = request.getTimestamp() == null ? date.getTime() : request.getTimestamp() * 1000;

            ActivityEventDTO activityEventDTO = new ActivityEventDTO();
            activityEventDTO.setIdempotent(idCreateorUtil.genId());
            activityEventDTO.setUid(uid);
            activityEventDTO.setEventInfo(JSON.toJSONString(request));
            activityEventDTO.setEventSource(ActivityEventSourceEnum.USER_REPORT.getCode());
            activityEventDTO.setCreateTime(date.getTime());
            activityEventDTO.setEventTime(eventTime);
            activityEventDTO.setEventType(ActivityEventTypeEnum.SPECIAL_INVITE.getCode());
            sendStandardEventMsg(activityEventDTO);
        }
    }

    @Override
    public void handleDistributionOrderMsg(DistributionOrderAggrVO request) {
        if (Objects.nonNull(request)) {
            DistributionOrderEvent distributionOrderEvent = new DistributionOrderEvent();
            Map<String, Object> extMap = request.getExtMap();
            if (Objects.isNull(extMap) || extMap.isEmpty()) {
                log.info("handleDistributionOrderMsg extMap is null,msg:{}", JSON.toJSONString(request));
                return;
            }
            if (StringUtils.isBlank(request.getOrderStatus())) {
                log.info("handleDistributionOrderMsg orderStatus is null,msg:{}", JSON.toJSONString(request));
                return;
            }
            String commissionStatus = String.valueOf(extMap.get("irisCommissionStatus"));
            if (!extMap.containsKey("cpsUid")) {
                log.info("handleDistributionOrderMsg cpsUid is null,msg:{}", JSON.toJSONString(request));
                return;
            }
            if (Objects.isNull(extMap.get("cpsUid"))) {
                log.info("handleDistributionOrderMsg cpsUid is null,msg:{}", JSON.toJSONString(request));
                return;
            }
            String cpsUid = String.valueOf(extMap.get("cpsUid"));
            if (StringUtils.isBlank(cpsUid)) {
                log.info("handleDistributionOrderMsg cpsUid is null str,msg:{}", JSON.toJSONString(request));
                return;
            }

            Long orderCreateTime = request.getOrderTime();
            Long gmv = request.getEstimatedDistributeAmount();
            String orderStatus = request.getOrderStatus();
            Long finishTime = request.getFinishTime();
            distributionOrderEvent.setGmv(gmv);
            distributionOrderEvent.setCommissionStatus(commissionStatus);
            distributionOrderEvent.setOrderCreateTime(orderCreateTime);
            distributionOrderEvent.setCpsUid(cpsUid);
            distributionOrderEvent.setOrderStatus(orderStatus);
            distributionOrderEvent.setFinishTime(finishTime);
            distributionOrderEvent.setId(request.getId());
            distributionOrderEvent.setOrderNo(request.getOrderNo());

            Date date = new Date();
            ActivityEventDTO activityEventDTO = new ActivityEventDTO();
            activityEventDTO.setIdempotent(idCreateorUtil.genId());
            activityEventDTO.setUid(cpsUid);
            activityEventDTO.setEventInfo(JSON.toJSONString(distributionOrderEvent));
            activityEventDTO.setEventSource(ActivityEventSourceEnum.USER_REPORT.getCode());
            activityEventDTO.setCreateTime(date.getTime());
            activityEventDTO.setEventTime(orderCreateTime);
            activityEventDTO.setEventType(ActivityEventTypeEnum.DISTRIBUTION_ORDER.getCode());

            //添加开关，控制分销单消息是否投递topic隔离
            if (BooleanUtils.isTrue(activityConfig.isOrderMsgTopicChange())) {
                sendStandardLowerPriorityEventMsg(activityEventDTO);
            } else {
                sendStandardEventMsg(activityEventDTO);
            }

        }
    }

    @Override
    public void sendStandardEventMsg(ActivityEventDTO activityEventDTO) {
        log.info("sendStandardEventMsg msg:{}", JSON.toJSONString(activityEventDTO));
        kafkaMsgSender.send(activityEventTopic, activityEventDTO.getUid(), JSON.toJSONString(activityEventDTO));
    }

    public void sendStandardLowerPriorityEventMsg(ActivityEventDTO activityEventDTO) {
        log.info("sendStandardLowerPriorityEventMsg msg:{}", JSON.toJSONString(activityEventDTO));
        kafkaMsgSender
                .send(activityLowerPriorityEventTopic, activityEventDTO.getUid(), JSON.toJSONString(activityEventDTO));
    }

}
